import { Component, OnInit, OnDestroy } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule, ReactiveFormsModule, FormGroup, FormBuilder, Validators } from '@angular/forms';
import { ListService, PagedResultDto } from '@abp/ng.core';
import { ThemeSharedModule } from '@abp/ng.theme.shared';
import { InventoryTransferService } from './inventory-transfer.service';
import { InventoryTransferDto, CreateUpdateInventoryTransferDto, InventoryTransferDetailDto } from './models';
import { ConfirmationService, Confirmation } from '@abp/ng.theme.shared';
import { ToasterService } from '@abp/ng.theme.shared';
import { Subscription } from 'rxjs';
import { lastValueFrom } from 'rxjs';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { finalize } from 'rxjs/operators';
import { ExcelExportService } from '../shared/services/excel-export.service';
import { StorehouseService } from '../FormWhx/storehouse/storehouse.service';
import { HttpClient } from '@angular/common/http';
import { Router } from '@angular/router';

@Component({
  selector: 'app-inventory-transfer',
  standalone: true,
  imports: [CommonModule, FormsModule, ReactiveFormsModule, ThemeSharedModule],
  templateUrl: './inventory-transfer.component.html',
  styleUrl: './inventory-transfer.component.scss',
  providers: [ListService]
})
export class InventoryTransferComponent implements OnInit, OnDestroy {
  inventoryTransfer = { items: [], totalCount: 0 } as PagedResultDto<InventoryTransferDto>;
  createInventoryTransferForm: FormGroup;
  isModalOpen = false;
  isEditMode = false;
  selectedInventoryTransferId: string;
  isSaving = false;
  Math = Math;
  
  // 复选框相关变量
  selectedItems: string[] = [];
  isAllSelected = false;
  
  // 状态选项
  statusOptions: string[] = [
    '待审核',
    '已审核',
    '调拨中',
    '已完成',
    '已取消'
  ];
  
  // 分页相关变量
  pageSizeOptions = [10, 20, 30, 50];
  currentPageSize = 10;
  maxPageCount = 1;
  visiblePageNumbers: number[] = [];
  inputPageNumber: number = 1;
  
  // 订阅对象
  private subscription: Subscription = new Subscription();
  
  // 搜索关键字属性
  transferNoKeyword = '';
  isSearchMode = false;
  
  // 加载状态
  isLoading = false;
  
  // 导出状态
  isExporting = false;
  
  // 类型选项
  transferTypeOptions: string[] = [
    '货品调拨',
    '库存预警',
    '满仓调离',
    '其他调拨'
  ];
  
  // 经办人选项
  handlerOptions: string[] = ['张三', '李四', '王五', '赵六'];
  
  // 调拨明细相关
  transferDetails: InventoryTransferDetailDto[] = [];
  selectedDetails: number[] = [];
  isAllDetailsSelected = false;
  
  warehouseOptions: string[] = [];
  
  showProductDialog = false;
  productList: any[] = [];
  
  isProductLoading = false;
  
  isAllProductChecked = false;
  
  constructor(
    public readonly list: ListService,
    private inventoryTransferService: InventoryTransferService,
    private fb: FormBuilder,
    private confirmation: ConfirmationService,
    private toaster: ToasterService,
    private modalService: NgbModal,
    private excelExportService: ExcelExportService,
    private storehouseService: StorehouseService,
    private http: HttpClient,
    private router: Router
  ) {
    this.createInventoryTransferForm = this.fb.group({
      transferNo: [''],
      sourceWarehouse: [''],
      targetWarehouse: [''],
      transferDate: [''],
      status: [''],
      totalAmount: [0],
      remarks: [''],
      transferType: [''],
      handler: ['']
    });
  }

  ngOnInit() {
    this.list.page = 1;
    this.loadData();
    this.loadWarehouseNames();
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }

  loadWarehouseNames() {
    this.storehouseService.getList({}).subscribe({
      next: (data) => {
        this.warehouseOptions = data.items.map(item => item.warehouseName) || [];
        console.log('Successfully loaded warehouse names:', this.warehouseOptions);
      },
      error: (err) => {
        console.error('Failed to load warehouse names:', err);
        this.toaster.error('仓库列表加载失败，详情请查看控制台日志', '错误');
      }
    });
  }

  // 加载数据并处理分页
  loadData() {
    if (this.list.page <= 0) {
      this.list.page = 1;
    }
    this.isLoading = true;
    const streamCreator = (query) => {
      const params = {
        ...query,
        maxResultCount: this.currentPageSize,
        skipCount: (this.list.page - 1) * this.currentPageSize
      };
      if (this.isSearchMode && this.transferNoKeyword.trim()) {
        return this.inventoryTransferService.searchByTransferNo(this.transferNoKeyword, params);
      } else {
        return this.inventoryTransferService.getList(params);
      }
    };
    this.subscription.add(
      this.list.hookToQuery(streamCreator)
        .pipe(
          finalize(() => {
            this.isLoading = false;
            this.selectedItems = [];
            this.isAllSelected = false;
          })
        )
        .subscribe(
          (response: PagedResultDto<InventoryTransferDto>) => {
            this.inventoryTransfer = response;
            if (response.totalCount > 0) {
              this.maxPageCount = Math.ceil(response.totalCount / this.currentPageSize);
              if (this.list.page > this.maxPageCount) {
                this.list.page = this.maxPageCount;
                if (response.items.length === 0) {
                  this.loadDataWithoutCheck();
                }
              }
            } else {
              this.maxPageCount = 1;
              this.list.page = 1;
            }
            // 批量请求每条调拨单明细，计算合计字段
            (this.inventoryTransfer.items || []).forEach(item => {
              this.inventoryTransferService.get(item.id).subscribe(detail => {
                const list = detail.merchandiseList || [];
                item.totalQuantity = list.reduce((sum, d) => sum + Number(d.merchandiseNumber || 0), 0);
                item.totalAmountSum = list.reduce((sum, d) => sum + Number(d.merchandisePrice || 0), 0);
                item.productNames = list.map(d => d.merchandiseName).join('，');
              });
            });
            this.updateVisiblePageNumbers();
          },
          error => {
            console.error('加载数据失败', error);
            let errorMessage = '加载数据失败，请稍后重试';
            if (error && error.error && error.error.message) {
              errorMessage = `${errorMessage}: ${error.error.message}`;
            }
            this.toaster.error(errorMessage, '错误', { life: 7000 });
          }
        )
    );
  }
  
  // 不进行页码检查的数据加载方法
  loadDataWithoutCheck() {
    this.isLoading = true;
    
    const streamCreator = (query) => {
      const params = {
        ...query,
        maxResultCount: this.currentPageSize,
        skipCount: (this.list.page - 1) * this.currentPageSize
      };
      
      if (this.isSearchMode && this.transferNoKeyword.trim()) {
        return this.inventoryTransferService.searchByTransferNo(this.transferNoKeyword, params);
      } else {
        return this.inventoryTransferService.getList(params);
      }
    };
    
    this.subscription.add(
      this.list.hookToQuery(streamCreator)
        .pipe(
          finalize(() => {
            this.isLoading = false;
          })
        )
        .subscribe(
          (response: PagedResultDto<InventoryTransferDto>) => {
            this.inventoryTransfer = response;
            this.updateVisiblePageNumbers();
          },
          error => {
            console.error('加载数据失败', error);
            this.toaster.error('加载数据失败', '错误');
          }
        )
    );
  }

  // 更新可见页码
  updateVisiblePageNumbers() {
    const currentPage = this.list.page || 1;
    const pageNumbers = [];
    
    if (this.maxPageCount <= 5) {
      for (let i = 1; i <= this.maxPageCount; i++) {
        pageNumbers.push(i);
      }
    } else {
      if (currentPage > 3) {
        pageNumbers.push(1, -1);
      }
      
      let start = Math.max(1, currentPage - 2);
      let end = Math.min(this.maxPageCount, currentPage + 2);
      
      for (let i = start; i <= end; i++) {
        pageNumbers.push(i);
      }
      
      if (end < this.maxPageCount) {
        pageNumbers.push(-1, this.maxPageCount);
      }
    }
    
    this.visiblePageNumbers = pageNumbers;
  }

  // 页面大小改变
  onPageSizeChange(pageSize: number) {
    this.currentPageSize = pageSize;
    this.list.page = 1;
    this.loadData();
  }

  // 跳转到指定页
  goToPage(page: number) {
    if (page < 1 || page > this.maxPageCount) return;
    this.list.page = page;
    this.loadData();
  }

  // 页码输入框变化
  onPageInputChange(event: Event) {
    const value = (event.target as HTMLInputElement).value;
    const page = Number(value);
    if (!isNaN(page)) {
      this.inputPageNumber = page;
    }
  }

  // 页码输入框回车
  onPageInputKeyUp(event: KeyboardEvent) {
    if (event.key === 'Enter') {
      this.goToPage(this.inputPageNumber);
    }
  }

  // 生成前端调拨单号（格式：DBDH+四位随机数）
  private generateFrontendTransferNo(): string {
    const random = Math.floor(Math.random() * 10000); // 0~9999
    return `DBDH${random.toString().padStart(4, '0')}`;
  }

  // 打开创建模态框
  openCreateModal() {
    this.isModalOpen = true;
    this.isEditMode = false;
    const transferNo = this.generateFrontendTransferNo();
    this.createInventoryTransferForm.reset({
      transferNo: transferNo, // 新建时直接赋值
      sourceWarehouse: '',
      targetWarehouse: '',
      transferDate: new Date().toISOString().split('T')[0],
      status: '待审核',
      totalAmount: 0,
      remarks: '',
      transferType: '',
      handler: ''
    });
  }

  // 打开编辑模态框
  openEditModal(inventoryTransferId: string) {
    this.isModalOpen = true;
    this.isEditMode = true;
    this.selectedInventoryTransferId = inventoryTransferId;
    this.inventoryTransferService.get(inventoryTransferId).subscribe(
      (data) => {
        const d: any = data;
        this.createInventoryTransferForm.patchValue({
          transferNo: d.inventoryTransferNo,
          sourceWarehouse: d.inventoryTransferOUT,
          targetWarehouse: d.inventoryTransferIN,
          transferDate: d.inventoryTransferDate ? d.inventoryTransferDate.substring(0, 10) : '',
          status: d.inventoryTransferOUTState,
          totalAmount: d.totalAmount,
          remarks: d.remarks,
          transferType: d.inventoryTransferType,
          handler: d.inventoryTransferOperator
        });
        // 明细回显，字段名映射，带上id
        this.transferDetails = (d.merchandiseList || []).map(item => ({
          id: item.id, // 主键
          GoodsId: item.goodsId || item.GoodsId,
          MerchandiseNo: item.merchandiseNo || item.MerchandiseNo,
          MerchandiseName: item.merchandiseName || item.MerchandiseName,
          MerchandiseModel: item.merchandiseModel || item.MerchandiseModel,
          MerchandiseUnit: item.merchandiseUnit || item.MerchandiseUnit,
          MerchandiseType: item.merchandiseType || item.MerchandiseType,
          MerchandiseOut: item.merchandiseOut || item.MerchandiseOut,
          MerchandiseIN: item.merchandiseIN || item.MerchandiseIN,
          MerchandiseNumber: item.merchandiseNumber || item.MerchandiseNumber,
          MerchandiseINPrice: item.merchandiseINPrice || item.MerchandiseINPrice,
          MerchandisePrice: item.merchandisePrice || item.MerchandisePrice,
          Reamres: item.reamres || item.Reamres
        }));
      },
      (error) => {
        this.toaster.error('加载库存调拨信息失败', '错误');
        this.closeModal();
      }
    );
  }

  // 打开详情模态框
  openDetailModal(inventoryTransferId: string) {
    this.isModalOpen = true;
    this.isEditMode = false; // 只读模式
    this.selectedInventoryTransferId = inventoryTransferId;
    this.inventoryTransferService.get(inventoryTransferId).subscribe(
      (data) => {
        const d: any = data;
        this.createInventoryTransferForm.patchValue({
          transferNo: d.inventoryTransferNo,
          sourceWarehouse: d.inventoryTransferOUT,
          targetWarehouse: d.inventoryTransferIN,
          transferDate: d.inventoryTransferDate ? d.inventoryTransferDate.substring(0, 10) : '',
          status: d.inventoryTransferOUTState,
          totalAmount: d.totalAmount,
          remarks: d.remarks,
          transferType: d.inventoryTransferType,
          handler: d.inventoryTransferOperator
        });
        this.transferDetails = (d.merchandiseList || []).map(item => ({
          id: item.id,
          GoodsId: item.goodsId,
          MerchandiseNo: item.merchandiseNo,
          MerchandiseName: item.merchandiseName,
          MerchandiseModel: item.merchandiseModel,
          MerchandiseUnit: item.merchandiseUnit,
          MerchandiseType: item.merchandiseType,
          MerchandiseOut: item.merchandiseOut,
          MerchandiseIN: item.merchandiseIN,
          MerchandiseNumber: item.merchandiseNumber,
          MerchandiseINPrice: item.merchandiseINPrice,
          MerchandisePrice: item.merchandisePrice,
          Reamres: item.reamres
        }));
      },
      (error) => {
        this.toaster.error('加载库存调拨信息失败', '错误');
        this.closeModal();
      }
    );
  }

  // 关闭模态框
  closeModal() {
    this.isModalOpen = false;
    this.createInventoryTransferForm.reset();
  }

  // 保存
  save() {
    const formValue = this.createInventoryTransferForm.value;
    const details = this.transferDetails.map(d => ({
      id: d.id,
      GoodsId: d.GoodsId,
      MerchandiseNo: d.MerchandiseNo,
      MerchandiseName: d.MerchandiseName,
      MerchandiseModel: d.MerchandiseModel,
      MerchandiseUnit: d.MerchandiseUnit,
      MerchandiseType: d.MerchandiseType,
      MerchandiseOut: d.MerchandiseOut,
      MerchandiseIN: d.MerchandiseIN,
      MerchandiseNumber: d.MerchandiseNumber != null ? String(d.MerchandiseNumber) : '',
      MerchandiseINPrice: Number(d.MerchandiseINPrice),
      MerchandisePrice: Number(d.MerchandisePrice),
      Reamres: d.Reamres
    }));

    const inventoryTransferData: any = {
      InventoryTransferNo: formValue.transferNo,
      InventoryTransferOUT: formValue.sourceWarehouse,
      InventoryTransferIN: formValue.targetWarehouse,
      InventoryTransferType: formValue.transferType,
      InventoryTransferOperator: formValue.handler,
      transferDate: formValue.transferDate,
      status: formValue.status,
      totalAmount: formValue.totalAmount,
      remarks: formValue.remarks,
      MerchandiseList: details
    };

    this.isSaving = true;
    if (this.isEditMode && this.selectedInventoryTransferId) {
      // 编辑模式，调用更新接口
      this.inventoryTransferService.update(this.selectedInventoryTransferId, inventoryTransferData).subscribe(
        res => {
          this.toaster.success('保存成功');
          this.isModalOpen = false;
          this.createInventoryTransferForm.reset();
          this.transferDetails = [];
          this.selectedDetails = [];
          this.loadData();
          this.isSaving = false;
        },
        err => {
          this.isSaving = false;
          console.error('保存失败', err);
        }
      );
    } else {
      // 新增模式
      this.inventoryTransferService.create(inventoryTransferData).subscribe(
        res => {
          this.toaster.success('保存成功');
          this.isModalOpen = false;
          this.createInventoryTransferForm.reset();
          this.transferDetails = [];
          this.selectedDetails = [];
          this.loadData();
          this.isSaving = false;
        },
        err => {
          this.isSaving = false;
          console.error('保存失败', err);
        }
      );
    }
  }

  // 删除库存调拨
  deleteInventoryTransfer(inventoryTransferId: string) {
    this.confirmation.warn('::AreYouSureToDelete', '::AreYouSure').subscribe((status) => {
      if (status === Confirmation.Status.confirm) {
        this.inventoryTransferService.delete(inventoryTransferId).subscribe(
          () => {
            if (this.inventoryTransfer.items.length === 1 && this.list.page > 1) {
              this.list.page--;
            }
            this.loadData();
            this.toaster.success('库存调拨已成功删除', '成功');
          },
          (error) => {
            let errorMessage = '删除库存调拨失败';
            if (error && error.error && error.error.message) {
              errorMessage += ': ' + error.error.message;
            }
            this.toaster.error(errorMessage, '错误');
          }
        );
      }
    });
  }

  // 搜索库存调拨
  searchInventoryTransfer() {
    this.isSearchMode = true;
    this.list.page = 1;
    this.loadData();
  }

  // 重置搜索
  resetSearch() {
    this.transferNoKeyword = '';
    this.isSearchMode = false;
    this.list.page = 1;
    this.loadData();
  }

  // 导出选中项
  async exportSelectedItems() {
    if (this.selectedItems.length === 0) {
      this.toaster.warn('请先选择要导出的项目', '提示');
      return;
    }

    this.isExporting = true;
    try {
      const selectedData = this.inventoryTransfer.items.filter(item => 
        this.selectedItems.includes(item.id)
      );
      
      // 转换为KehuDto格式以兼容现有的导出服务
      const kehuData = selectedData.map(item => ({
        id: item.id,
        name: item.InventoryTransferNo || '',
        contactPerson: item.InventoryTransferOUT || '',
        phone: item.InventoryTransferIN || '',
        mobile: item.transferDate || '',
        address: item.status || '',
        enterpriseAttribute: item.totalAmount?.toString() || '',
        contractNumber: item.remarks || '',
        contact1: item.creatorName || '',
        phone1: item.creationTime || '',
        emailAddress: '',
        remarks: ''
      }));
      
      await this.excelExportService.exportKehuToExcel(kehuData, '库存调拨选中项');
      this.toaster.success('导出成功', '成功');
    } catch (error) {
      this.toaster.error('导出失败', '错误');
    } finally {
      this.isExporting = false;
    }
  }

  // 导出当前页
  async exportCurrentPage() {
    this.isExporting = true;
    try {
      // 转换为KehuDto格式以兼容现有的导出服务
      const kehuData = this.inventoryTransfer.items.map(item => ({
        id: item.id,
        name: item.InventoryTransferNo || '',
        contactPerson: item.InventoryTransferOUT || '',
        phone: item.InventoryTransferIN || '',
        mobile: item.transferDate || '',
        address: item.status || '',
        enterpriseAttribute: item.totalAmount?.toString() || '',
        contractNumber: item.remarks || '',
        contact1: item.creatorName || '',
        phone1: item.creationTime || '',
        emailAddress: '',
        remarks: ''
      }));
      
      await this.excelExportService.exportKehuToExcel(kehuData, '库存调拨当前页');
      this.toaster.success('导出成功', '成功');
    } catch (error) {
      this.toaster.error('导出失败', '错误');
    } finally {
      this.isExporting = false;
    }
  }

  // 导出所有数据
  exportAllData() {
    this.confirmation.warn('导出所有数据可能需要较长时间，确定继续吗？', '确认导出').subscribe((status) => {
      if (status === Confirmation.Status.confirm) {
        this.exportAllDataInternal();
      }
    });
  }

  private async exportAllDataInternal() {
    this.isExporting = true;
    
    try {
      const fetchAllData = () => {
        return new Promise<any[]>((resolve, reject) => {
          const allData: any[] = [];
          let currentPage = 1;
          const pageSize = 1000;
          
          const fetchPage = () => {
            const params = {
              skipCount: (currentPage - 1) * pageSize,
              maxResultCount: pageSize
            };
            
            this.inventoryTransferService.getList(params).subscribe(
              (response) => {
                allData.push(...response.items);
                
                if (response.items.length === pageSize && allData.length < response.totalCount) {
                  currentPage++;
                  fetchPage();
                } else {
                  resolve(allData);
                }
              },
              (error) => {
                reject(error);
              }
            );
          };
          
          fetchPage();
        });
      };
      
      const allData = await fetchAllData();
      
      // 转换为KehuDto格式以兼容现有的导出服务
      const kehuData = allData.map(item => ({
        id: item.id,
        name: item.InventoryTransferNo || '',
        contactPerson: item.InventoryTransferOUT || '',
        phone: item.InventoryTransferIN || '',
        mobile: item.transferDate || '',
        address: item.status || '',
        enterpriseAttribute: item.totalAmount?.toString() || '',
        contractNumber: item.remarks || '',
        contact1: item.creatorName || '',
        phone1: item.creationTime || '',
        emailAddress: '',
        remarks: ''
      }));
      
      await this.excelExportService.exportKehuToExcel(kehuData, '库存调拨全部数据');
      this.toaster.success('导出成功', '成功');
    } catch (error) {
      this.toaster.error('导出失败', '错误');
    } finally {
      this.isExporting = false;
    }
  }

  // 全选/取消全选
  selectAll(checked: boolean): void {
    this.isAllSelected = checked;
    if (checked) {
      this.selectedItems = this.inventoryTransfer.items.map(item => item.id);
    } else {
      this.selectedItems = [];
    }
  }

  // 切换单个项目选择状态
  toggleItemSelection(id: string): void {
    const index = this.selectedItems.indexOf(id);
    if (index > -1) {
      this.selectedItems.splice(index, 1);
    } else {
      this.selectedItems.push(id);
    }
    
    // 更新全选状态
    this.isAllSelected = this.selectedItems.length === this.inventoryTransfer.items.length;
  }

  // 删除选中项
  deleteSelected(): void {
    if (this.selectedItems.length === 0) {
      this.toaster.warn('请先选择要删除的项目', '提示');
      return;
    }

    this.confirmation.warn(`确定要删除选中的 ${this.selectedItems.length} 个项目吗？`, '确认删除').subscribe((status) => {
      if (status === Confirmation.Status.confirm) {
        const deletePromises = this.selectedItems.map(id => 
          this.inventoryTransferService.delete(id).toPromise()
        );
        
        Promise.all(deletePromises).then(() => {
          this.loadData();
          this.toaster.success('选中项目已成功删除', '成功');
        }).catch((error) => {
          this.toaster.error('删除失败', '错误');
        });
      }
    });
  }

  // 调拨明细相关方法
  addDetail() {
    this.transferDetails.push({
      InventoryTranId: 0,
      GoodsId: undefined,
      MerchandiseNo: '',
      MerchandiseName: '',
      MerchandiseModel: '',
      MerchandiseUnit: '',
      MerchandiseType: '',
      MerchandiseOut: '',
      MerchandiseIN: '',
      MerchandiseNumber: '',
      MerchandiseINPrice: 0,
      MerchandisePrice: 0,
      Reamres: ''
    });
  }

  removeDetail(index: number) {
    const detail = this.transferDetails[index];
    // 先弹窗确认
    this.confirmation.warn('确定要删除该明细吗？', '确认删除').subscribe((status) => {
      if (status === Confirmation.Status.confirm) {
        if (detail.id) {
          const id = String(detail.id);
          this.inventoryTransferService.deleteDetail(id).subscribe({
            next: () => {
              this.transferDetails.splice(index, 1);
              this.selectedDetails = this.selectedDetails.filter(i => i !== index);
              this.updateSelectAllState();
              this.calculateAmount();
              this.toaster.success('明细已成功删除', '成功');
            },
            error: () => {
              this.toaster.error('明细删除失败，请稍后重试', '错误');
            }
          });
        } else {
          // 仅前端移除
          this.transferDetails.splice(index, 1);
          this.selectedDetails = this.selectedDetails.filter(i => i !== index);
          this.updateSelectAllState();
          this.calculateAmount();
          this.toaster.success('明细已移除', '成功');
        }
      }
    });
  }

  removeDetails() {
    if (this.selectedDetails.length === 0) return;
    
    // 从大到小排序，以便正确删除
    const sortedIndexes = [...this.selectedDetails].sort((a, b) => b - a);
    sortedIndexes.forEach(index => {
      this.transferDetails.splice(index, 1);
    });
    
    this.selectedDetails = [];
    this.isAllDetailsSelected = false;
    this.calculateAmount();
  }

  toggleDetailSelection(index: number) {
    const pos = this.selectedDetails.indexOf(index);
    if (pos > -1) {
      this.selectedDetails.splice(pos, 1);
    } else {
      this.selectedDetails.push(index);
    }
    this.updateSelectAllState();
  }

  toggleAllDetails(event: any) {
    const checked = event.target.checked;
    this.isAllDetailsSelected = checked;
    this.selectedDetails = checked ? this.transferDetails.map((_, index) => index) : [];
  }

  updateSelectAllState() {
    this.isAllDetailsSelected = this.transferDetails.length > 0 && 
                               this.selectedDetails.length === this.transferDetails.length;
  }

  getTotalQuantity(): number {
    return this.transferDetails.reduce((sum, detail) => {
      return sum + (Number(detail.MerchandiseNumber) || 0);
    }, 0);
  }

  getTotalAmount(): number {
    return this.transferDetails.reduce((sum, detail) => {
      return sum + (Number(detail.MerchandisePrice) || 0);
    }, 0);
  }

  calculateDetailAmount(detail: InventoryTransferDetailDto) {
    // 校验调拨数量不能大于调出仓库当前库存
    const quantity = Number(detail.MerchandiseNumber) || 0;
    const outStock = Number(detail.MerchandiseOut) || 0;
    if (quantity > outStock) {
      detail.MerchandiseNumber = String(outStock);
      this.toaster.warn('调拨数量不能大于调出仓库当前库存', '提示');
    }
    const price = Number(detail.MerchandiseINPrice) || 0;
    detail.MerchandisePrice = (Number(detail.MerchandiseNumber) || 0) * price;
    this.calculateAmount();
  }

  calculateAmount() {
    const totalAmount = this.getTotalAmount();
    this.createInventoryTransferForm.patchValue({
      totalAmount: totalAmount
    }, { emitEvent: false });
  }

  // 取消按钮处理
  cancel() {
    // 如果在模态框中，则关闭模态框
    if (this.isModalOpen) {
      this.closeModal();
    }
    // 如果是独立页面，则返回列表
    else {
      // 实现返回逻辑
    }
  }

  openProductDialog() {
    this.showProductDialog = true;
    this.productList = [];
    this.isProductLoading = true;
    this.http.get<any>('/api/app/goods-app-servicezmy').subscribe({
      next: (res) => {
        this.productList = Array.isArray(res.items) ? res.items : [];
        this.isProductLoading = false;
      },
      error: (err) => {
        this.toaster.error('货品数据加载失败', '错误');
        this.isProductLoading = false;
      }
    });
  }

  closeProductDialog() {
    this.showProductDialog = false;
  }

  toggleAllProductChecked() {
    this.productList.forEach(item => item.checked = this.isAllProductChecked);
  }

  onProductCheckedChange() {
    this.isAllProductChecked = this.productList.length > 0 && this.productList.every(item => item.checked);
  }

  confirmSelectProduct() {
    const selectedProducts = this.productList.filter(item => item.checked);
    selectedProducts.forEach(product => {
      this.transferDetails.push({
        id: product.id,
        GoodsId: product.goodsId,
        MerchandiseNo: product.merchandiseNo,
        MerchandiseName: product.merchandiseName,
        MerchandiseModel: product.merchandiseModel,
        MerchandiseUnit: product.merchandiseUnit,
        MerchandiseType: '商品',
        MerchandiseOut: product.merchandiseIN,
        MerchandiseIN: product.merchandiseIN,
        MerchandiseNumber: '',
        MerchandiseINPrice: product.merchandiseINPrice,
        MerchandisePrice: 0,
        Reamres: ''
      });
    });
    this.closeProductDialog();
  }

  goToDetail(inventoryTransferId: string) {
    this.router.navigate(['/inventoryTransfer/detail', inventoryTransferId]);
  }
} 